<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\URL;
use App\Models\Permission;
use  Cache;

class GetMenu
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /*
         *view()->share('comData',$this->getMenu());
         *此写法也可，但是在mainSiderbar模板里要删掉
         *<?php $comData=Request::get('comData_menu'); ?>
         * 也就是下面写法得到comData_menu的方式
        */
        $request->attributes->set('comData_menu', $this->getMenu());
        return $next($request);
    }

    /**
     * 获取左边菜单栏
     * @return array
     */
    function getMenu()
    {
        //拿到所有的权限
        $permissions = Permission::orderBy("id")->get();
        foreach ($permissions as $key => $value) {
            if (!Gate::check($value['name'])) {
                unset($permissions[$key]);
            }
        }
        $permissions = $permissions->toArray();
        $menus = [];
        $count = $active = 0;
        foreach ($permissions as $key => $value) {
            //用gate判断当前角色所拥有的权限
            if ($value['pid'] == 0) {
                if ($count == 0) {
                    $active = $key;
                    $count = 1;
                }
                $menus[$key] = $value;
                foreach ($permissions as $mm => $nn) {
                    if ($nn['pid'] == $value['id']) {
                        $menus[$active]['active'][$nn['name']] = $value['id'];
                    }
                    if ((($nn['pid'] == $value['id']) && (strpos($nn['name'], 'index') !== false)) || (($nn['pid'] == $value['id']) && (strpos($nn['name'], 'list') !== false))) {
                        $menus[$key]['children'][] = $nn;
                    }
                }
                if (empty($menus[$key]['children'])) {
                    $menus[$key]['children'] = [];
                }
            }
        }
        return array_values($menus);
    }
}
